<?php

namespace app\facade;

use think\facade\Env;
use app\facade\Redis;

class Mns
{


    private $time = 180;

    public function send($mobile = null, $data = [])
    {
        $statusStr = array(
            "0" => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
        );
        $SendRes = [
            'status' => false,
            'msg' => '发送失败'
        ];
        $MnsRds = 'MnsRds' . $mobile;
        $MnsTime = Redis::get($MnsRds);
        if ($MnsTime) {
            $SendRes['msg'] = '短信发送频繁请' . ($MnsTime - time()) . 's后发送';
            return $SendRes;
        }
        $code = rand(1000, 9999);
        $content = '【万果门】您的验证码为：' . $code . '，有效期为' . ($this->time / 60) . '分钟，请勿泄露于他人！';
        $content = urlencode($content);
        $url = 'https://api.smsbao.com/sms?u=15897381680&p=72fb090a74464805887d9b670dc594f2&m=' . $mobile . '&c=' . $content;
        $result = file_get_contents($url);
        if ($result == 0) {
            $res = Redis::setex($mobile, $this->time, $code);
            if ($res) {
                Redis::setex($MnsRds, 60, time() + 60);
                $SendRes = [
                    'status' => true,
                    'msg' => '发送成功'
                ];
                return $SendRes;
            }
        } else {
            $SendRes['msg'] = $statusStr[$result] ?? '发送失败';
            return $SendRes;
        };
    }

    public function checkCode($code = null, $mobile = null)
    {
        if (!Env::get('sms.open')) {
            return true;
        }
        $check = Redis::get($mobile);
        if ($check && ($mobile !== null)) {
            if ($check == $code) {
                Redis::del($mobile);
                return true;
            }
            return false;
        }
        return false;
    }
}
